package com.chy.service;

import com.alibaba.fastjson.JSON;
import com.chy.pojo.Content;
import com.chy.utils.HtmlParseUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ContentService
{
    @Autowired
    RestHighLevelClient restHighLevelClient;




    public Boolean parseContent(String keywords) throws IOException
    {
        List<Content> contents = new HtmlParseUtils().parseKey(keywords);

        //把查询到的数据放入es中

        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");

        for (int i = 0; i <contents.size() ; i++)
        {
            bulkRequest.add(
                    new IndexRequest("jd_goods")
                    .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
            );
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }


    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws IOException
{
    if(pageNo<=1){
        pageNo = 1;
    }

    //条件搜索
    SearchRequest searchRequest = new SearchRequest("jd_goods");
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

    //分页
    sourceBuilder.from(pageNo);
    sourceBuilder.size(pageSize);


    //精确匹配
    TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
    sourceBuilder.query(termQueryBuilder);
    sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

    //执行搜索

    searchRequest.source(sourceBuilder);
    SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

    ArrayList<Map<String,Object>> lists = new ArrayList<>();
    //解析结果
    for (SearchHit documentFields: search.getHits().getHits()
    )
    {
        lists.add(documentFields.getSourceAsMap());
    }
    return lists;



}


    public List<Map<String,Object>> searchHighLightPage(String keyword,int pageNo,int pageSize) throws IOException
    {
        if(pageNo<=1){
            pageNo = 1;
        }

        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        highlightBuilder.field("name");
        sourceBuilder.highlighter(highlightBuilder);


        //精确匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索

        searchRequest.source(sourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        ArrayList<Map<String,Object>> lists = new ArrayList<>();
        //解析结果
        for (SearchHit hit: search.getHits().getHits()
        )
        {
            //解析高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            //原来的结果
            HighlightField name1 = highlightFields.get("name");
//            System.out.println(name1+"==============");
            String new_name = "";
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if(name1 !=null){
                Text[] fragments = name1.fragments();
                for (Text fragment : fragments) {
                    new_name += fragment;
                }
            }
            sourceAsMap.put("name", new_name);
            lists.add(sourceAsMap);
        }
        return lists;



    }
}
